package com.softroad.help.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;

import android.app.Application;
import android.content.Context;
import android.util.Xml;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.softroad.help.app.bean.UserBean;
import com.softroad.help.app.tools.NetworkTool;

/**
 * 
 * @brief 整个应用程序Applicaiton
 * @author Fanhao.Yi
 * @date 2015年4月23日下午7:01:20
 * @version V1.0
 */
public class MyApplication extends Application {

	/** 对外提供整个应用生命周期的Context **/
	private static Context instance;
	/** 整个应用全局可访问数据集合 **/
	private static Map<String, Object> gloableData = new HashMap<String, Object>();

	protected static UserBean userBean;
	protected static boolean isLogin = false;
	protected static BDLocation location;

	public BDLocation getLocation() {
		return location;
	}

	public void setLocation(BDLocation location) {
		MyApplication.location = location;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		MyApplication.userBean = userBean;
	}

	public boolean isLogin() {
		setLogin(false);
		if (isReadDataCache("user")) {
			UserBean userBean = (UserBean) readObject("user");
			if (userBean != null && userBean.getUserId() > 0) {
				setUserBean(userBean);
				setLogin(true);
			}
		}
		return isLogin;
	}

	public void setLogin(boolean isLogin) {
		MyApplication.isLogin = isLogin;
	}

	/**
	 * 对外提供Application Context
	 * 
	 * @return
	 */
	public static Context gainContext() {
		return instance;
	}

	public void onCreate() {
		super.onCreate();
		instance = this;
		initImageLoader(getApplicationContext());
		SDKInitializer.initialize(this);
	}

	public static void initImageLoader(Context context) {
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs().build();
		ImageLoader.getInstance().init(config);
	}

	// 解析assets目录下的XML文件
	private List<Map> readAssetsXML(Context context, String fileName) {
		XmlPullParser parser = Xml.newPullParser();

		try {
			InputStream inStream = context.getAssets().open(fileName);
			parser.setInput(context.getAssets().open(fileName), "UTF-8");
			int eventType = parser.getEventType();

			Map currentMap = null;
			List<Map> list = null;

			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
					list = new ArrayList<Map>();
					break;

				case XmlPullParser.START_TAG:// 开始元素事件
					currentMap = new HashMap();
					int count = parser.getAttributeCount();
					for (int i = 0; i < count; i++) {
						currentMap.put(parser.getAttributeName(i),
								parser.getAttributeValue(i));
					}
					break;

				case XmlPullParser.END_TAG:// 结束元素事件
					if (currentMap != null) {
						list.add(currentMap);
						currentMap = null;
					}
					break;
				}
				eventType = parser.next();
			}
			inStream.close();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void onTerminate() {
		super.onTerminate();

	}

	/**
	 * 获取网络是否已连接
	 * 
	 * @return
	 */
	public static boolean isNetworkReady() {
		return NetworkTool.getInstance().init(instance).isConnected();
	}

	/******************************************************* Application数据操作API（开始） ********************************************************/

	/**
	 * 往Application放置数据（最大不允许超过5个）
	 * 
	 * @param strKey
	 *            存放属性Key
	 * @param strValue
	 *            数据对象
	 */
	public static void assignData(String strKey, Object strValue) {
		if (gloableData.size() > 5) {
			throw new RuntimeException("超过允许最大数");
		}
		gloableData.put(strKey, strValue);
	}

	/**
	 * 从Applcaiton中取数据
	 * 
	 * @param strKey
	 *            存放数据Key
	 * @return 对应Key的数据对象
	 */
	public static Object gainData(String strKey) {
		return gloableData.get(strKey);
	}

	/*
	 * 从Application中移除数据
	 */
	public static void removeData(String key) {
		if (gloableData.containsKey(key))
			gloableData.remove(key);
	}

	/**
	 * -------------------------------对象缓存--------------------------------------
	 * -
	 */
	public boolean isReadDataCache(String cachefile) {
		return readObject(cachefile) != null;
	}

	private boolean isExistDataCache(String cachefile) {
		boolean exist = false;
		File data = getFileStreamPath(cachefile);
		if (data.exists())
			exist = true;
		return exist;
	}

	public boolean saveObject(Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = openFileOutput(file, MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				oos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	public Serializable readObject(String file) {
		if (!isExistDataCache(file)) {
			return null;
		}
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
		} catch (Exception e) {
			e.printStackTrace();

			if (e instanceof InvalidClassException) {
				File data = getFileStreamPath(file);
				data.delete();
			}
		} finally {
			try {
				ois.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return null;
	}

	public void deleteObject(String file) {
		if (!isExistDataCache(file)) {
			return;
		}
		File data = getFileStreamPath(file);
		data.delete();
	}
	/**
	 * ---------------------------------对象缓存结束----------------------------------
	 */
}
